package cn.fl.collection.service.impl;

import cmm.comm.facade.upload.api.IUploadApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.collection.api.IRskCltAuthApiService;
import cn.fl.collection.api.IRskCltAuthRcvAplApiService;
import cn.fl.collection.condition.RskCltAuthRcvAplQC;
import cn.fl.collection.constant.CollectionConstant;
import cn.fl.collection.dto.RskCltAuthDTO;
import cn.fl.collection.dto.RskCltAuthRcvAplDTO;
import cn.fl.collection.service.IRskCltAuthRebateService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.constant.PrjPrdPaySchMConstant;
import cn.fl.project.dto.ProjectFlowSHDTO;
import cn.fl.system.transform.SysUlFilesRecVOTransform;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.upload.constant.UploadConstant;
import com.google.common.collect.Lists;
import fl.flow.facade.flow.api.IFlowQueryApiService;
import fl.flow.facade.flow.condition.SysFlowSHQueryCondition;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.SysFlowSHDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @Description:    委外催收回款接口实现类
* @Author:         liurong
* @CreateDate:     2020/4/23 9:57
* @Version:        1.0
*/
@Service
public class RskCltAuthRebateServiceImpl implements IRskCltAuthRebateService {

	@Autowired
	private IRskCltAuthRcvAplApiService rskCltAuthRcvAplApiService;

	@Autowired
	private IRskCltAuthApiService rskCltAuthApiService;

	@Autowired
	private IUploadApiService uploadApiService;

	@Autowired
	private IFlowQueryApiService flowQueryApiService;

	@Autowired
	private ISysOrgApiService sysOrgApiService;

	@Autowired
	private ISysUsrApiService sysUsrApiService;

	/**
	 * 新增回款并发起委外催收回款流程
	 * @param applyDTO
	 * @param fileList
	 * @throws BaseException
	 */
	@Override
	public DataResultDTO addApplyAndStartFlow(RskCltAuthRcvAplDTO applyDTO, List<SysUlFilesRecVO> fileList) throws BaseException {
		try {
			// 启动流程参数
			FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
			flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
			flowStartParamsDTO.setWordsInTheTable(CollectionConstant.WORD_TABLE_RSK);
			flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
			flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
			flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
			flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);//优先级,可以在界面定义
			flowStartParamsDTO.setBusinessType(CollectionConstant.TAB_NM);
			flowStartParamsDTO.setModelTyp(CollectionConstant.RSK_CLT_AUTH_FLOW_CD);
			applyDTO.setFlowStartParamsDTO(flowStartParamsDTO);
			// 新增申请并启动流程
			DataResultDTO dataResultDTO = rskCltAuthRcvAplApiService.addApplyAndStartFlow(applyDTO);

			if (dataResultDTO != null && dataResultDTO.getSuccess() == BaseConstant.IS_YESNO_YES) {
				Long applyId = (Long) dataResultDTO.getData();
				try {
					// 上传附件
					for (SysUlFilesRecVO sysUlFilesRecVO : fileList) {
						sysUlFilesRecVO.setTabNm(CollectionConstant.TAB_NM);
						sysUlFilesRecVO.setIsDel(BaseConstant.IS_YESNO_NO);
						sysUlFilesRecVO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
						sysUlFilesRecVO.setSysCd(CurrentThreadContext.getCurrentSysCd());
						sysUlFilesRecVO.setCfgCd(CollectionConstant.CLT_AUTH_FILE_CFG_FLOW);
						sysUlFilesRecVO.setCfgDtlCd(PrjPrdPaySchMConstant.PRJ_PRD_Pay_SCH_M_FILE_DETAIL_CODE);
						sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH) + sysUlFilesRecVO.getFilePath());
						sysUlFilesRecVO.setPkId(applyId.toString());
						sysUlFilesRecVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
						sysUlFilesRecVO.setCrtTm(new Date());
						sysUlFilesRecVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
						sysUlFilesRecVO.setMdfTm(new Date());
						uploadApiService.addSysUlFilesRec(SysUlFilesRecVOTransform.toDTO(sysUlFilesRecVO));
					}
				} catch (Exception e) {
					BaseLogUtils.newLogger(applyId + "发起委外催收回款流程附件上传失败！").setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0003);
				}
			}
			return dataResultDTO;
		} catch (BaseException e) {
			throw e;
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 查询流程跟踪数据
	 * 通过cltAuthId获取回款申请ID列表，然后查询流程发起历史
	 * @param cltAuthId
	 * @return
	 * @throws BaseException
	 */
	@Override
	public List<ProjectFlowSHDTO> searchFlowListByCltAuthId(Long cltAuthId) throws BaseException {

		RskCltAuthDTO rskCltAuthDTO = rskCltAuthApiService.selectById(cltAuthId);
		if (rskCltAuthDTO == null) {
			throw new BaseException("委外催收数据不存在！");
		}
		List<ProjectFlowSHDTO> list = Lists.newArrayList();
		RskCltAuthRcvAplQC condition = new RskCltAuthRcvAplQC();
		condition.setCltAuthId(cltAuthId);
		condition.setIsDel(BaseConstant.IS_YESNO_NO);
		List<RskCltAuthRcvAplDTO> applyDTOS = rskCltAuthRcvAplApiService.searchList(condition);
		if (CollectionUtils.isEmpty(applyDTOS)) {
			return list;
		}
		List<Long> applyIds = applyDTOS.stream().map(RskCltAuthRcvAplDTO::getId).collect(Collectors.toList());

		SysFlowSHQueryCondition flowQueryCondition = new SysFlowSHQueryCondition();
		flowQueryCondition.setDataIdList(applyIds);
		flowQueryCondition.setSysCd(CurrentThreadContext.getCurrentSysCd());
		flowQueryCondition.setWordsInTheTable(CollectionConstant.WORD_TABLE_RSK);
		List<SysFlowSHDTO> flowList = flowQueryApiService.searchFlowSHList(flowQueryCondition);

		if (CollectionUtils.isNotEmpty(flowList)) {
			List<Long> usrIds = flowList.stream().map(SysFlowSHDTO::getCrtUsrId).collect(Collectors.toList());
			Map<Long, SysUsrDTO> sysUsrMap = null;
			if (CollectionUtils.isNotEmpty(usrIds)) {
				SysUsrQueryCondition sysUsrQC = new SysUsrQueryCondition();
				sysUsrQC.setUsrIds(usrIds);
				sysUsrQC.setSysCd(CurrentThreadContext.getCurrentSysCd());
				List<SysUsrDTO> sysUsrDTOList = sysUsrApiService.searchSysUsrList(sysUsrQC);
				if (CollectionUtils.isNotEmpty(sysUsrDTOList)) {
					sysUsrMap = sysUsrDTOList.stream().collect(Collectors.toMap(SysUsrDTO::getId, SysUsrDTO -> SysUsrDTO));
				}
			}
			for (SysFlowSHDTO sysFlowSHDTO : flowList) {
				ProjectFlowSHDTO projectFlowSHDTO = new ProjectFlowSHDTO();
				BeanUtils.copyProperties(sysFlowSHDTO, projectFlowSHDTO);

				projectFlowSHDTO.setGrpFlag(rskCltAuthDTO.getPaySchNo());
				if (sysUsrMap != null && sysUsrMap.containsKey(projectFlowSHDTO.getCrtUsrId())) {
					projectFlowSHDTO.setCrtUsrName(sysUsrMap.get(projectFlowSHDTO.getCrtUsrId()).getRefRlNm());
				}

				list.add(projectFlowSHDTO);
			}
		}
		return list;
	}

	/**
	 *回款管理列表
	 * @param page
	 * @return
	 * @throws BaseException
	 */
	@Override
	public Pager selectRskCltAuthRcvAplPage(Pager page) throws BaseException {

		if(null == page)page = new Pager();
		page = rskCltAuthRcvAplApiService.selectRskCltAuthRcvAplPage(page);
		List<RskCltAuthRcvAplDTO> rskCltAuthRcvAplDTOList = (List<RskCltAuthRcvAplDTO>)page.getResultList();
		if(CollectionUtils.isNotEmpty(rskCltAuthRcvAplDTOList)){
			//添加省公司 事业部
			for(RskCltAuthRcvAplDTO r : rskCltAuthRcvAplDTOList){
				//省公司
				String cstMgrOrgNm = null;
				if(StringUtils.isNotEmpty(r.getCstMgrOrgCd())){
					cstMgrOrgNm = sysOrgApiService.selectSysOrgNmByOrgCd(r.getCstMgrOrgCd(), CurrentThreadContext.getCurrentSysCd());;
				}
				//事业部
				String buOrgNm = "";
				if(StringUtils.isNotEmpty(r.getBuOrgCd())){
					buOrgNm = sysOrgApiService.selectSysOrgNmByOrgCd(r.getBuOrgCd(),CurrentThreadContext.getCurrentSysCd());
				}
				//催收机构(委案机构)
				String authOrgNm = "";
				if(StringUtils.isNotEmpty(r.getAuthOrgCd())){
					authOrgNm = sysOrgApiService.selectSysOrgNmByOrgCd(r.getAuthOrgCd(),CurrentThreadContext.getCurrentSysCd());
				}
				r.setAuthOrgNm(authOrgNm);
				r.setCstMgrOrgNm(cstMgrOrgNm);
				r.setBuOrgNm(buOrgNm);
			}
		}
		page.setResultList(rskCltAuthRcvAplDTOList);
		return page;
	}

	@Override
	public List<RskCltAuthRcvAplDTO> selectList(RskCltAuthRcvAplQC condition){
		condition.setIsDel(BaseConstant.IS_YESNO_NO);
		List<RskCltAuthRcvAplDTO> applyDTOS = rskCltAuthRcvAplApiService.searchList(condition);
		return applyDTOS;
	}

	/**
	 * 列表
	 * @return
	 */
	@Override
	public List<RskCltAuthRcvAplDTO> selectRskCltAuthRcvAplList(RskCltAuthRcvAplQC qc){
		return rskCltAuthRcvAplApiService.selectRskCltAuthRcvAplList(qc);
	}

}
